/* Copyright (c) [Year] [name of copyright holder]
 * [Software Name] is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *      http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.gitee.empty_null.core.config;

import com.gitee.empty_null.core.filter.DelegateRequestInterceptor;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Optional;

/**
 * @author xuhainan
 * @date 2023/8/25 13:52
 * @region hefei
 */
public class UnionWebMvcConfigurer implements WebMvcConfigurer, ApplicationContextAware {

    private DelegateRequestInterceptor delegateRequestInterceptor;

    @Override
    public void addInterceptors(@NotNull InterceptorRegistry registry) {
        Optional.ofNullable(delegateRequestInterceptor.webRequestInterceptors())
                .ifPresent(webRequestInterceptors -> webRequestInterceptors.forEach(registry::addWebRequestInterceptor));
        Optional.ofNullable(delegateRequestInterceptor.handlerInterceptors())
                .ifPresent(handlerInterceptors -> handlerInterceptors.forEach(registry::addInterceptor));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        delegateRequestInterceptor = applicationContext.getBean(DelegateRequestInterceptor.class);
    }
}
